package com.pansoft.openplanet.activity;

import android.animation.ObjectAnimator;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.zxing.qrcode.QRCode;
import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.fragment.BottomAssetChooseDialogFragment;
import com.pansoft.openplanet.util.ChainParamsUtil;
import com.utilcode.util.LogUtils;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static android.app.DialogFragment.STYLE_NO_FRAME;

/**
 * 转入资产二维码页面
 */
public class BarcodeReceiveActivity extends BaseActivity implements View.OnClickListener {

    private ImageView qrCodeIv;
    TextView tvLable;
    TextView tvWalletName;
    TextView tvAddress;
    LinearLayout llChangeAsset;
    LinearLayout llSpecifyAmount;
    ImageView ivEthAvatar;
    private TextView mTvSwitchAddress,mMainAddress,mChildAddress;
    private FrameLayout mFlSwitchAddress;
    private String walletName;
    private String walletAddress;
    private String tokenAddress;
    private String assetName;
    private String amount = "";
    private String tokenId = "";
    private Account account;
    private int chainId;
    private boolean isMianAddress = true;
    private String mainWalletAddress;
    /**
     * @param walletName    账户名
     * @param walletAddress 账户地址
     * @param assetName     代币名
     * @param assetAddress  代币地址
     * @param tokenId       代币编号
     * @param chainId       所属链编号
     */
    public static void start(Context context, String walletName, String walletAddress, String walletIcon,
                             String assetName, String assetAddress, int chainId, String tokenId) {
        Intent starter = new Intent(context, BarcodeReceiveActivity.class);
        starter.putExtra("walletName", walletName);
        starter.putExtra("walletAddress", walletAddress);
        starter.putExtra("walletIcon", walletIcon);
        starter.putExtra("assetName", assetName);
        starter.putExtra("assetAddress", assetAddress);
        starter.putExtra("chainId", chainId);
        starter.putExtra("tokenId", tokenId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_acitivty_barcode_receive);
        walletName = getIntent().getStringExtra("walletName");
        walletAddress = getIntent().getStringExtra("walletAddress");
        mainWalletAddress = walletAddress;
        chainId = getIntent().getIntExtra("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);
        assetName = getIntent().getStringExtra("assetName");
        if (StringUtils.isEmpty(assetName)) {
            assetName = "ETE";
        }
        tokenAddress = getIntent().getStringExtra("assetAddress");
        tokenId = getIntent().getStringExtra("tokenId");
        initView();

        generateQRCode();
    }


    private void initView() {


        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_trade_in));

        tvWalletName = (TextView) findViewById(R.id.tv_wallet_name);
        tvWalletName.setText(walletName);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvAddress.setText(walletAddress);
        tvAddress.setOnClickListener(this);
        tvLable = (TextView) findViewById(R.id.tv_lable);
        tvLable.setText(getString(R.string.open_planet_please_trade_in, amount, assetName));
//        if (getIntent().getIntExtra("mode", WalletListFragment.MODE_ETH) == WalletListFragment.MODE_ETH) {
//
//        }else {
//            tvLable.setText("请转入BTC");
//        }
        qrCodeIv = (ImageView) findViewById(R.id.qrCodeIv);

        llChangeAsset = (LinearLayout) findViewById(R.id.ll_change_asset);
        llChangeAsset.setOnClickListener(this);
        if (ChainParamsUtil.isChainHasNoTokens(chainId)) {
            llChangeAsset.setVisibility(View.GONE);
        }else {
            llChangeAsset.setVisibility(View.VISIBLE);
        }
        llSpecifyAmount = (LinearLayout) findViewById(R.id.ll_specify_amount);
        llSpecifyAmount.setOnClickListener(this);
        ivEthAvatar = (ImageView) findViewById(R.id.iv_eth_avatar);
        LXGlideImageLoader.getInstance().displayRoundCornerImage(this, ivEthAvatar, getIntent()
                        .getStringArrayExtra("walletIcon"), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon,
                20);

        mTvSwitchAddress = (TextView) findViewById(R.id.tv_switch_address);
        mMainAddress = (TextView) findViewById(R.id.tv_main_address);
        mChildAddress = (TextView) findViewById(R.id.tv_child_address);
        mFlSwitchAddress = (FrameLayout) findViewById(R.id.fl_switch_address);
        mMainAddress.setOnClickListener(this);
        mChildAddress.setOnClickListener(this);

        /**
         * 是否显示主地址和子地址切换布局 判断子地址是否为空
         */
        if(chainId == IPAssetsConstant.CHAIN_ID_BTC){
            AccountDao accountDao = new AccountDao(this);
            account = accountDao.getCurrentShowAccount(chainId);
            if(!StringUtils.isEmpty(account.getHdBtcCurrentChildAddress())){
                LogUtils.e("当前子地址---->"+account.getHdBtcCurrentChildAddress());
                mFlSwitchAddress.setVisibility(View.VISIBLE);
            }

        }

    }

    /**
     * 生成付款二维码
     */
    private void generateQRCode() {
        //@{@"walletAddress": self.walletModel.address, @"isTokenAcount": @(self.isTokenAccount),
        // @"tokenAddress": tokenAddress, @"amount": @"", @"tokenAddress": @""}
        Map<String, Object> map = new HashMap<>();
        map.put("type", "tokenTrade");
        map.put("tokenUnit", assetName);
        //转入地址
        map.put("walletAddress", walletAddress);
        //转入数量
        map.put("amount", amount);
        //合约地址
        map.put("contractAddress", tokenAddress);

        if (ChainParamsUtil.isTokenAccount(tokenAddress, assetName)) {
            map.put("isTokenAccount", true);
        } else {
            map.put("isTokenAccount", false);
        }
        map.put("chainId", chainId+"");
        map.put("tokenId", tokenId);
        Bitmap bitmap = QRCode.setQRcode(new JSONObject(map).toString(), SizeUtils.dp2px(150), SizeUtils.dp2px(150));
        qrCodeIv.setImageBitmap(bitmap);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        //选择收款资产
        if (id == R.id.ll_change_asset) {
            showAssetChoose();
        } else if (id == R.id.ll_specify_amount) {
            //选择收款数额
            showAmountInput();
        }else if(id == R.id.tv_main_address){
            //切换主地址
            if(!isMianAddress){
                isMianAddress = true;
                switchMainAddress();
            }

        }else if(id == R.id.tv_child_address){
            //切换子地址
            if(isMianAddress){
                isMianAddress = false;
                switchChildAddress();
            }
        } else if (id == R.id.tv_address) {
            //复制地址
            copyAddress(tvAddress.getText().toString(), ResStringUtil.getString(R.string.chat_copy_to_clipboard));
        }
    }

    //复制地址
    private void copyAddress(String address, String toast) {
        //复制账号
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(address);
        ToastUtils.setBgColor(getResources().getColor(R.color.black));
        ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
        ToastUtils.showShort(toast);
    }

    /**
     * 切换子地址方法
     */
    private void switchChildAddress() {
        //1、mTvSwitchAddress重新赋值
        mTvSwitchAddress.setText(R.string.star_asset_sub_address);
        tvAddress.setText(account.getHdBtcCurrentChildAddress());
        //2、执行切换到子地址动画
        executeAnim(0, mChildAddress.getMeasuredWidth());
        //3、更换子地址的二维码
        // TODO: 2019/11/6  更换子地址的二维码
        walletAddress = account.getHdBtcCurrentChildAddress();
        generateQRCode();
    }

    /**
     * 切换主地址方法
     *
     */
    private void switchMainAddress() {
        //1、mTvSwitchAddress重新赋值
        mTvSwitchAddress.setText(R.string.star_asset_main_address);
        tvAddress.setText(mainWalletAddress);
        //2、执行切换动画
        executeAnim(mChildAddress.getX(), 0);

        //3、更换主地址的二维码
        // TODO: 2019/11/6  更换主地址的二维码
        walletAddress = mainWalletAddress;
        generateQRCode();
    }

    /**
     * 选择代币
     * 选择后刷新界面
     */
    private void showAssetChoose() {
        BottomAssetChooseDialogFragment bottomAssetChooseDialogFragment = new
                BottomAssetChooseDialogFragment();
        bottomAssetChooseDialogFragment.setData(this, walletAddress, assetName);
        bottomAssetChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomAssetChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomAssetChooseDialogFragment.setOnAssetSelectChangedListener(new BottomAssetChooseDialogFragment.OnAssetSelectChangedListener() {
            @Override
            public void onAssetChanged(AssetListBean assetListBean) {
                assetName = assetListBean.getName();
                tokenAddress = assetListBean.getAddress() == null ? "" : assetListBean.getAddress();
                tvLable.setText(getString(R.string.open_planet_please_trade_in, amount, assetName));
                tokenId = assetListBean.getId()==null?"": assetListBean.getId();
                generateQRCode();
            }
        });
    }

    private void showAmountInput() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                com.efounder.chat.R.layout.social_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = (EditText) layout
                .findViewById(com.efounder.chat.R.id.ed_name);
        ed_name.setHint(ResStringUtil.getString(R.string.open_planet_input_trade_in_amount));
        ed_name.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        ed_name.setSelection(ed_name.getText().length());
        //限制EditText输入数字
        ed_name.addTextChangedListener(new NumberTextWatcher(ed_name));
        dialog.setTitle(ResStringUtil.getString(R.string.open_planet_input_amount));
        dialog.setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String newName = ed_name.getText().toString().trim();
                        if (newName.equals("")) {
                            return;
                        } else {
                            //调用接口
                            amount = newName;
                            tvLable.setText(getString(R.string.open_planet_please_trade_in, amount, assetName));
                            generateQRCode();
                        }
                        dialog.cancel();
                    }


                });
        dialog.setNegativeButton(R.string.common_text_cancel, null);
        dialog.show();
    }

    /**
     * 切换地址的动画效果
     * @param startLocation
     * @param endLocation
     */
    private void executeAnim(float startLocation,float endLocation){
        ObjectAnimator translationXAnimator = ObjectAnimator.ofFloat(mTvSwitchAddress, "translationX", startLocation, endLocation);
        translationXAnimator.setDuration(400);
        translationXAnimator.start();
    }
}
